package com.pzb.wechat.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.pzb.common.config.WechatConfig;
import com.pzb.common.utils.StringUtils;
import com.pzb.common.utils.http.HttpUtils;
import com.pzb.wechat.domain.WechatComponent;
import com.pzb.wechat.mapper.WechatComponentMapper;
import com.pzb.wechat.service.IWechatComponentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 三方信息Service业务层处理
 * 
 * @author Mr_Wu
 * @date 2021-12-31
 */
@Service
public class WechatComponentServiceImpl implements IWechatComponentService 
{
    private static final Logger log = LoggerFactory.getLogger(WechatComponentServiceImpl.class);

    private final String API_URL = "https://api.weixin.qq.com/cgi-bin/component";

    @Autowired
    private WechatComponentMapper wechatComponentMapper;

    /**
     * 查询三方信息
     *
     * @return 三方信息
     */
    @Override
    public WechatComponent selectWechatComponent()
    {
        return wechatComponentMapper.selectWechatComponent();
    }

    /**
     * 修改三方信息
     *
     * @param wechatComponent 三方信息
     * @return 结果
     */
    @Override
    public int updateWechatComponent(WechatComponent wechatComponent)
    {
        return wechatComponentMapper.updateWechatComponent(wechatComponent);
    }

    @Override
    public String getApiComponentAccessToken() {
        //先查询是否过期
        WechatComponent component = selectWechatComponent();
        //计算时间差
        Double min = (new Date().getTime()-component.getTokenCreateTime().getTime())/(1000*60)*1.0;
        //如果大于110分钟重新获取
        if(min < 110){
            return component.getComponentAccessToken();
        }
        //获取AccessToken
        JSONObject param = new JSONObject();
        param.put("component_appid", WechatConfig.getAppId());
        param.put("component_appsecret", WechatConfig.getAppSecret());
        param.put("component_verify_ticket", component.getTicket());
        String result =  HttpUtils.sendPost(API_URL+"/api_component_token",param.toString());
        JSONObject object = JSONObject.parseObject(result);
        String component_access_token = object.getString("component_access_token");
        if(StringUtils.isNotBlank(component_access_token)){
            component.setComponentAccessToken(component_access_token);
            component.setTokenCreateTime(new Date());
            component.setTicket(null);
            component.setTicketCreateTime(null);
            updateWechatComponent(component);
        }else {
            log.info("获取AccessToken失败=================>"+result);
        }
        return component_access_token;
    }

}
